package org.sunrise.game.client.main.frame;

import org.sunrise.game.client.client.SocketClient;
import org.sunrise.game.client.client.SocketClientManager;
import org.sunrise.game.client.gen.ChatProto;
import org.sunrise.game.client.gen.TopicProto;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ChatRoom extends JFrame {
    public static ChatRoom instance;
    private JTextArea chatArea; // 聊天记录显示区域
    private JTextField inputField; // 消息输入框
    private JButton sendButton; // 发送按钮

    public ChatRoom() {
        // 设置窗口标题
        setTitle("Chat");
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null); // 窗口居中

        // 初始化聊天记录区域
        chatArea = new JTextArea();
        chatArea.setEditable(false); // 禁止编辑
        chatArea.setLineWrap(true); // 自动换行
        JScrollPane scrollPane = new JScrollPane(chatArea); // 添加滚动条
        add(scrollPane, BorderLayout.CENTER);

        // 初始化底部面板（输入框和发送按钮）
        JPanel bottomPanel = new JPanel(new BorderLayout());
        inputField = new JTextField();
        sendButton = new JButton("发送");

        // 发送按钮点击事件
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });

        // 输入框回车事件
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });

        bottomPanel.add(inputField, BorderLayout.CENTER);
        bottomPanel.add(sendButton, BorderLayout.EAST);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    // 发送消息
    private void sendMessage() {
        String message = inputField.getText().trim();
        if (!message.isEmpty()) {
            SocketClient client = SocketClientManager.getInstance();
            client.sendMsg(TopicProto.MBasePacketData.newBuilder()
                    .setPacketType(TopicProto.TOPIC.TOPIC_TYPE_CHAT)
                    .setPacketId(ChatProto.FROM_CLIENT.C2S_Chat_VALUE)
                    .setPacketData(ChatProto.MC2S_Chat.newBuilder().setType(1).setMsg(message).build().toByteString())
                    .build());
            inputField.setText(""); // 清空输入框
        }
    }

    // 显示消息
    public void displayMessage(String name, String message, long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String timeStr = sdf.format(new Date(time));
        String formattedMessage = String.format("[%s][%s]：%s\n",
                timeStr, name, message);
        chatArea.append(formattedMessage);
    }
}